<template>
  <el-drawer v-model="drawerVisible" :destroy-on-close="true" size="450px" :title="`${drawerProps.title}`">
    <el-tree
      ref="treeRef"
      :data="drawerProps.menuList"
      show-checkbox
      node-key="id"
      :default-expand-all="true"
      :props="defaultProps"
      :default-checked-keys="cheked"
    />
    <template #footer>
      <el-button @click="drawerVisible = false"> 取消 </el-button>
      <el-button v-show="!drawerProps.isView" type="primary" @click="handleSubmit"> 确定 </el-button>
    </template>
  </el-drawer>
</template>

<script setup lang="ts" name="UserDrawer">
import { ref } from "vue"; //reactive
//import { genderType } from "@/utils/serviceDict";
import { ElMessage, ElTree } from "element-plus";
import { User } from "@/api/interface"; //
import { getMenuByRoleId, insertMenuRole } from "@/api/modules/sys";
//import UploadImg from "@/components/Upload/Img.vue";
// import UploadImgs from "@/components/Upload/Imgs.vue";
const defaultProps = {
  children: "children",
  label: "name"
};
interface DrawerProps {
  title: string;
  isView: boolean;
  row: Partial<User.ResUserList>;
  api?: (params: any) => Promise<any>;
  getTableList?: () => void;
  menuList: any;
}

const drawerVisible = ref(false);
let cheked = ref();
const drawerProps = ref<DrawerProps>({
  isView: false,
  title: "",
  row: {},
  menuList: []
});
// 获取权限值
const getChecked = async () => {
  const { data } = await getMenuByRoleId({ roleId: drawerProps.value.row?.id });
  data?.forEach(item => {
    treeRef.value?.setChecked(item, true, false);
  });
};
// 接收父组件传过来的参数
const acceptParams = async (params: DrawerProps) => {
  drawerProps.value = params;
  drawerVisible.value = true;
  getChecked();
};

// 提交数据（新增/编辑）
const treeRef = ref<InstanceType<typeof ElTree>>();
const handleSubmit = async () => {
  let list = treeRef.value?.getCheckedNodes(false, true);
  list = list?.map(item => item.id);
  if (list && list.length) {
    try {
      await insertMenuRole({
        roleId: drawerProps.value.row?.id,
        menuIdList: list
      });
      ElMessage.success({ message: `${drawerProps.value.title}角色成功！` });
      // drawerProps.value.getTableList!();
      getChecked();
      drawerVisible.value = false;
    } catch (error) {
      console.log(error);
    }
  } else {
    ElMessage.warning("请选择");
  }

  // });
};

defineExpose({
  acceptParams
});
</script>
